<?php

namespace app\partner\controller;

use app\common\controller\CommonService;
use think\facade\Cache;
use think\facade\Validate;
use think\Controller;
use think\Request;
use think\Db;

class Login extends Controller
{
    /**
     * 合伙人第一次登陆找回密码时发送验证码
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * */
    public function checkTel(Request $request)
    {
        $requestData = $request->post();
        $validate = Validate::make([
            'tel|手机号' => 'require',
        ]);
        if (!$validate->check($requestData)){
            return CommonService::error($validate->getError());
        }
        $userId = Db::name('user_manage')
            ->where('tel',$requestData['tel'])
            ->value('id');
        if (empty($userId)){
            return CommonService::error(6);
        }
        $partnerId = Db::name('partner')
            ->where('uid',$userId)
            ->value('id');
        if (empty($partnerId)){
            return CommonService::error(1);
        }
        $templateParam['code'] = mt_rand(1000, 9999);
        $send = CommonService::sendSms($requestData['tel'], $templateParam, 'SMS_175535973');
        if ($send) {
            if (Cache::get('sendSmsCount' . $requestData['tel']) <= 0) {
                $time = strtotime(date('Y-m-d')) + 86400 - time();
                Cache::set('sendSmsCount' . $requestData['tel'], 1, $time);
            } else {
                Cache::inc('sendSmsCount' . $requestData['tel'], 1);
            }
            Cache::set('smsCode' . $requestData['tel'], $templateParam['code'], 300);
            return CommonService::success('', '验证码已发送！');
        } else {
            return CommonService::error(3);
        }
    }

    /**
     * 验证验证码
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * */
    public function checkPartner(Request $request)
    {
        $requestData = $request->post();
        $validate = Validate::make([
            'tel|手机号' => 'require',
            'code|验证码' => 'require',
        ]);
        if (!$validate->check($requestData)){
            return CommonService::error($validate->getError());
        }
        $userId = Db::name('user_manage')
            ->where('tel',$requestData['tel'])
            ->value('id');
        if (empty($userId)){
            return CommonService::error(1);
        }
        $partnerId = Db::name('partner')
            ->where('uid',$userId)
            ->value('id');
        if (empty($partnerId)){
            return CommonService::error(1);
        }
        if ($requestData['code'] != Cache::get('smsCode' . $requestData['tel'])) {
            return CommonService::error(5);
        }
        $data['partner_id'] = $partnerId;
        return CommonService::success($data);
    }

    /**
     * 设置密码
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * */
    public function setPassword(Request $request)
    {
        $requestData = $request->post();
        $validate = Validate::make([
            'partner_id|合伙人' => 'require',
            'password|密码' => 'require',
            'password1|重复密码' => 'require',
        ]);
        if (!$validate->check($requestData)){
            return CommonService::error($validate->getError());
        }
        $userId = Db::name('partner')
            ->where('id',$requestData['partner_id'])
            ->find();
        if (empty($userId)){
            return CommonService::error(1);
        }
        $userInfo = Db::name('user_manage')
            ->where('id',$userId['uid'])
            ->value('id');
        if (empty($userInfo)){
            return CommonService::error(1);
        }
        if ($requestData['password'] != $requestData['password1']){
            return CommonService::error(105);
        }
        if ($userId['password'] == md5($requestData['password'])){
            return CommonService::error(108);
        }
        $result = Db::name('partner')->where('id', $userId['id'])->update([
            'password' => md5($requestData['password']),
        ]);
        if ($result){
            return CommonService::success('','密码设置成功！');
        } else {
            return CommonService::error(0);
        }
    }

    /**
     * 合伙人登陆
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * */
    public function login(Request $request)
    {
        $requestData = $request->post();
        $validate = Validate::make([
            'tel|手机号' => 'require',
            'password|密码' => 'require',
        ]);
        if (!$validate->check($requestData)){
            return CommonService::error($validate->getError());
        }
        $userInfo = Db::name('user_manage')
            ->where('tel',$requestData['tel'])
            ->field('id,nickname,xingming,headimgurl')
            ->find();
        if (empty($userInfo['id'])){
            return CommonService::error(2);
        }
        $partnerInfo = Db::name('partner')
            ->where('uid',$userInfo['id'])
            ->field('id,password,status')
            ->find();
        if (empty($partnerInfo)){
            return CommonService::error(2);
        }
        switch ($partnerInfo['status']) {
            case 0:
                return CommonService::error(10);
            case 1:
                break;
            case 2:
            case 3:
                return CommonService::error(11);
            default:
                return CommonService::error(12);
        }
        if ($partnerInfo['password'] != md5($requestData['password'])){
            return CommonService::error(2);
        }
        Db::name('login_log')->insert([
           'uid' => $partnerInfo['id'],
           'login_time' => time(),
           'login_ip' => $request->ip(),
           'login_area' => CommonService::getAttributionByIp($request->ip()),
           'login_browser' => CommonService::getBrowserInfo(request()->header()),
           'user_type' => 2,
       ]);
        $responseData['partnerToken'] = CommonService::jwtEncode(['id' => $partnerInfo['id']], time() + 86400);
        $responseData['headimgurl'] = $userInfo['headimgurl'];
        $responseData['nickname'] = CommonService::emoji_decode($userInfo['nickname']);
        $responseData['xingming'] = $userInfo['xingming'];
        cache('partnerAdmin' . $partnerInfo['id'], $responseData['partnerToken'], 86400);
        return CommonService::success($responseData);
    }
}
